package system.schedule;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import system.base.InOutCal;


import framework.core.DBConnection;
import framework.core.DBEngine;
import framework.core.DBPreparedStatement;
import framework.core.DBResult;
import framework.core.DateUtil;
import framework.core.LogWriter;

public class InOutInfoJob implements Job{
	
    private static boolean isRunning = false;

	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		if(!isRunning){
			myRun();
		}else{
			System.out.println("-----------------------------");
		}
	}
	
	private void myRun() {
    	isRunning = true;
    	DBPreparedStatement db = null;
    	DBConnection con = null;
    	try {
			con = DBConnection.open(false);
			con.setAutoCommit(false);
			String sql = "delete from t_out_in_info";
			db =con.prepareStatement(sql);
			db.executeUpdate();
			String insert = InOutCal.inOutSql(con, (new DateUtil()).getFullString());
			db =con.prepareStatement(insert);
			db.executeUpdate();
			String findCompanyWarehouseCode = "select substr(warehouse_code,0,6) warehouse_code from  t_out_in_info where length(warehouse_code) >=6 group by substr(warehouse_code,0,6)   order by substr(warehouse_code,0,6)";
		    LogWriter.info(sql);
		    DBResult result = null;
		    try{
		        result = DBEngine.doSelect(con, findCompanyWarehouseCode);
		        java.sql.ResultSet rs = result.getRs();
		        while(rs.next()){
		          	String obj = rs.getString("warehouse_code");
		            String insertSql = "insert into t_out_in_info select '"+obj+"', sum(year_in),sum(year_out),sum(month_in),sum(month_out),sum(day_in),sum(day_out) from t_out_in_info where warehouse_code like  '"+obj+"%'";
		            db = con.prepareStatement(insertSql);
		            db.executeUpdate();
		        }
		     }finally{
		        if(result!=null) result.clear() ;
		     }
			con.commit();
		} catch (Exception e) {
			try {
				con.rollback();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
            try {
            	if(db!=null){
            		db.close();
            	}
                if (con != null){
                    con.close();
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            isRunning = false;
        }
      
	}

}
